//Page Object
import { request } from "../../request/index.js";

Page({
  data: {
    goodsObj: []
  },
  GoodsInfo: "",
  //options(Object)
  onLoad: function (options) {
    const { goods_id } = options;
    this.getgoodsdetail(goods_id);
  },
  //item(index,pagePath,text)
  onTabItemTap: function (item) { },
  // 获取商品详情数据
  async getgoodsdetail(goods_id) {
    const res = await request({
      url: "/goods/detail",
      data: {
        goods_id
      }
    });
    this.GoodsInfo = res.data.message;
    this.setData({
      goodsObj: {
        goods_name: res.data.message.goods_name,
        goods_price: res.data.message.goods_price,
        goods_introduce: res.data.message.goods_introduce.replace(
          /\.webp/g,
          ".jpg"
        ),
        pics: res.data.message.pics
      }
    });
  },
  handlePrevewImage(e) {
    const urls = this.GoodsInfo.pics.map(v => v.pics_mid);
    const current = e.currentTarget.dataset.url;
    wx.previewImage({
      current, // 当前显示图片的http链接
      urls // 需要预览的图片http链接列表
    });
  },
  handleCartAdd() {
    let cart = wx.getStorageSync("cart") || [];
    let index = cart.findIndex(v => v.goods_id === this.GoodsInfo.goods_id);
    if (index === -1) {
      this.GoodsInfo.num = 1;
      this.GoodsInfo.checked = true;
      cart.push(this.GoodsInfo);
    } else {
      cart[index].num++;
    }

    wx.setStorageSync("cart", cart);
    wx.showToast({
      title: "加入成功",
      icon: "success",
      //防手抖多次点击
      mask: true,
      success: result => { },
      fail: () => { },
      complete: () => { }
    });
  }
});
